package com.hspedu.bot.service.impl.user.bot;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hspedu.bot.pojo.Bot;
import com.hspedu.bot.pojo.User;
import com.hspedu.bot.service.user.bot.BotService;
import com.hspedu.bot.service.user.bot.AddService;
import com.hspedu.bot.utils.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AddServiceImpl implements AddService {

    @Autowired
    private BotService botService;

    @Override
    public Map<String, String> add(Map<String, String> data) {

        UsernamePasswordAuthenticationToken authenticationToken =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser = (UserDetailsImpl) authenticationToken.getPrincipal();
        User user = loginUser.getUser();

        String title = data.get("title");
        String description = data.get("description");
        String content = data.get("content");

        //处理异常
        Map<String, String> map = new HashMap<>();
        if (!StringUtils.hasText(title)) {
            map.put("error_message", "标题不能为空");
            return map;
        }

        if (title.length() > 100) {
            map.put("error_message", "标题长度不能大于100");
            return map;
        }

        if (!StringUtils.hasText(description)) {
            description = "这个用户很懒,什么都没留下~";
        }

        if (description.length() > 300) {
            map.put("error_message", "Bot描述长度不能大于300");
            return map;
        }

        if (!StringUtils.hasText(content)) {
            map.put("error_message", "内容不能为空");
            return map;
        }

        if (content.length() > 10000) {
            map.put("error_message", "内容长度不能大于10000");
            return map;
        }

        //防止bot添加过多(一个用户限制最多10个)
        QueryWrapper<Bot> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        if (botService.count(queryWrapper) >= 5) {
            map.put("error_message", "允许添加bot个数已满(最多5个)");
            return map;
        }

        //添加Bot
        Date date = new Date();
        Bot bot =
                new Bot(null, user.getId(), title, description, content, date, date);
        botService.save(bot);

        map.put("error_message", "success");
        return map;
    }
}
